package com.github.shiqiyue.app.config.captcha;

import com.github.shiqiyue.app.common.utils.HttpServletRequestUtils;

import java.util.Objects;

public class SessionCaptchaStore implements ICaptchaStore {

    /***
     * 验证码 key 前缀
     */
    private static final String SESSION_KEY_CAPTCHA_PREFIX = "captcha:";

    @Override
    public void store(String captcha, Integer captchaType) {
        Objects.requireNonNull(HttpServletRequestUtils.getSession()).setAttribute(SESSION_KEY_CAPTCHA_PREFIX + captchaType, captcha);
    }

    @Override
    public boolean match(String captcha, Integer captchaType, Boolean ignoreCase) {
        String storeCaptcha = (String) Objects.requireNonNull(HttpServletRequestUtils.getSession()).getAttribute(SESSION_KEY_CAPTCHA_PREFIX + captchaType);
        if (storeCaptcha == null) {
            return false;
        }
        if (ignoreCase) {
            return captcha.equalsIgnoreCase(storeCaptcha);
        } else {
            return captcha.equals(storeCaptcha);
        }
    }
}
